<template>
  <div class="moment-detail-container">
    <!-- 顶部导航 -->
    <div class="detail-header">
      <button class="back-btn" @click="goBack">
        <i class="back-icon">‹</i>
      </button>
      <h1 class="header-title">详情</h1>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner">加载中...</div>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-message">{{ error }}</div>
      <button class="retry-btn" @click="loadMomentDetail">重试</button>
    </div>
    
    <!-- 内容区域 -->
    <div v-else class="detail-content">
      <!-- 用户信息 -->
      <div class="user-section">
        <img :src="moment.user.avatar" :alt="moment.user.name" class="user-avatar" />
        <div class="user-info">
          <h2 class="user-name">{{ moment.user.name }}</h2>
          <!-- 文字内容 -->
          <div v-if="moment.text" class="text-content">{{ moment.text }}</div>
        </div>
      </div>

      <!-- 媒体内容 -->
      <div class="media-content">
        <!-- 图片 -->
        <div v-if="moment.images && moment.images.length > 0" class="images-section">
          <div class="images-grid">
            <div v-for="(image, index) in moment.images" :key="index" class="image-item" @click="previewImage(image, moment.images, index)">
              <img :src="image" :alt="`图片${index + 1}`" />
            </div>
          </div>
        </div>

        <!-- 视频 -->
        <div v-if="moment.video" class="video-section">
          <video :src="moment.video" controls :poster="moment.videoPoster"></video>
        </div>

        <!-- 位置 -->
        <div v-if="moment.location" class="location-section">
          <i class="location-icon">📍</i>
          <span>{{ moment.location }}</span>
        </div>

        <!-- 发布时间和操作按钮 -->
        <div class="time-actions-section">
          <p class="post-time">{{ moment.time }}</p>
          <div class="action-buttons">
            <button 
              class="action-btn like-btn" 
              :class="{ 'liked': isLiked }"
              @click="toggleLike"
            >
              <i class="like-icon">{{ isLiked ? '❤️' : '🤍' }}</i>
            </button>
            <button 
              v-if="isOwner" 
              class="action-btn delete-btn-small" 
              @click="deleteMoment"
            >
              <i class="delete-icon">🗑️</i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 点赞区域 -->
    <div v-if="moment.likes && moment.likes.length > 0" class="likes-section">
      <i class="heart-icon">❤️</i>
      <div class="likes-avatars">
        <img 
          v-for="like in moment.likes" 
          :key="like.id" 
          :src="like.avatar" 
          :alt="like.name" 
          class="like-avatar" 
          :title="like.name" 
        />
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section" v-if="moment.comments.length > 0">
      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-for="(comment, index) in moment.comments" :key="comment.id" class="comment-item" @click="replyToComment(comment)" :class="{ 'first-comment': index === 0 }">
          <i v-if="index === 0" class="comment-icon">💬</i>
          <div v-else class="comment-icon-placeholder"></div>
          <img :src="comment.user.avatar" :alt="comment.user.name" class="comment-avatar" />
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-user">{{ comment.user.name }}</span>
              <span class="comment-time">{{ comment.time }}</span>
            </div>
            <div class="comment-text" >
              <span v-if="comment.replyTo" class="reply-mention">@{{ comment.replyTo }}: </span>
              {{ comment.text }}
            </div>
        </div>
        </div>
      </div>

    </div>


    <!-- 评论输入框固定在底部 -->
    <div class="comment-input-fixed">
              <div class="comment-input-container">
          <input 
            v-model="newComment" 
            type="text" 
            :placeholder="replyingTo ? `回复 @${replyingTo.user.name}` : '留点什么吧...'" 
            class="comment-input"
            @keyup.enter="addComment"
            @blur="handleInputBlur"
          />
          <button @click="addComment" class="send-comment-btn" :disabled="!newComment.trim()">
            评论
          </button>
        </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer 
      v-if="imagePreview.visible"
      :url-list="imagePreview.urlList"
      :initial-index="imagePreview.initialIndex"
      @close="closeImagePreview"
      teleported
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import api from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { lo } from 'element-plus/es/locales.mjs'

interface User {
  id: number
  name: string
  avatar: string
}

interface Comment {
  id: number
  user: User
  text: string
  time: string
  replyTo?: string
  pid?: number
}

interface Moment {
  id: number
  user: User
  text?: string
  images?: string[]
  video?: string
  videoPoster?: string
  location?: string
  time: string
  likes: User[]
  comments: Comment[]
}

const router = useRouter()
const route = useRoute()

// Data - 初始化为空对象
const moment = ref<Moment>({
  id: 0,
  user: {
    id: 0,
    name: '',
    avatar: ''
  },
  text: '',
  images: [],
  video: '',
  videoPoster: '',
  location: '',
  time: '',
  likes: [],
  comments: []
})

const newComment = ref('')
const replyingTo = ref<Comment | null>(null)
const isLiked = ref(false)
const currentUserId = ref()
const loading = ref(true)
const error = ref('')
const userName = ref('')
const avatar = ref('')

// Image preview
const imagePreview = reactive({
  visible: false,
  urlList: [] as string[],
  initialIndex: 0
})

// Computed
const isOwner = computed(() => currentUserId.value == moment.value.user.id)

// Methods
const goBack = () => {
  router.back()
}

const previewImage = (image: string, images: string[], index: number) => {
  imagePreview.visible = true
  imagePreview.urlList = images
  imagePreview.initialIndex = index
}

const closeImagePreview = () => {
  imagePreview.visible = false
}

const addComment = async () => {
  if (!newComment.value.trim()) return
  
  try {
    const commentData = {
      momentId: moment.value.id,
      userId: currentUserId.value,
      content: newComment.value.trim(),
      pid: replyingTo.value?.id || 0
    }
    
    const response = await api.post('/moments/comment/publish', commentData)
    
    if (response.data && response.data.code === 200) {
      // 添加评论到本地列表
      const newCommentItem: Comment = {
        id: Date.now(), // 临时ID，实际应该从后端返回
        user: {
          id: currentUserId.value,
          name: userName.value,
          avatar: avatar.value
        },
        text: newComment.value.trim(),
        time: formatTime(new Date().toISOString()),
        replyTo: replyingTo.value ? replyingTo.value.user.name : undefined,
        pid: replyingTo.value?.id || 0
      }
      moment.value.comments.push(newCommentItem)
      
      newComment.value = ''
      replyingTo.value = null
      ElMessage.success('评论发布成功')
    }
  } catch (error) {
    console.error('发布评论失败:', error)
    ElMessage.error('评论发布失败')
  }
}

const deleteMoment = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条朋友圈吗？',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await api.delete(`/moments/moment/deleteMoments/${moment.value.id}`)
    ElMessage.success('删除成功')
    router.back()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换点赞状态
const toggleLike = async () => {
  try {
    if (isLiked.value) {
      // 取消点赞
      await api.delete(`/moments/likes/unlikeMoment/${moment.value.id}/${currentUserId.value}`)
      isLiked.value = false
      // 从点赞列表中移除当前用户
      moment.value.likes = moment.value.likes.filter(like => like.id != currentUserId.value)
      ElMessage.success('取消点赞')
    } else {
      // 点赞
      await api.post(`/moments/likes/likeMoment/${moment.value.id}/${currentUserId.value}`)
      isLiked.value = true
      // 添加当前用户到点赞列表
      const currentUser = {
        id: currentUserId.value,
        name: userName.value,
        avatar: avatar.value
      }
      if (!moment.value.likes.find(like => like.id == currentUserId.value)) {
        moment.value.likes.unshift(currentUser)
      }
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
    // 发生错误时恢复状态
    isLiked.value = !isLiked.value
  }
}

// 回复评论
const replyToComment = (comment: Comment) => {
  replyingTo.value = comment
  // 滚动到底部的评论输入框
  setTimeout(() => {
    const inputElement = document.querySelector('.comment-input-fixed .comment-input') as HTMLInputElement
    if (inputElement) {
      inputElement.focus()
      // 滚动到底部
      window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
    }
  }, 100)
}

// 处理输入框失去焦点
const handleInputBlur = () => {
  // 使用 setTimeout 避免与点击发送按钮冲突
  setTimeout(() => {
    if (!newComment.value.trim()) {
      replyingTo.value = null
    }
  }, 150)
}

// 加载朋友圈详情
const loadMomentDetail = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const momentId = route.query.id
    if (!momentId) {
      error.value = '朋友圈ID不能为空'
      return
    }
    
    const response = await api.get(`/moments/moment/getMomentsById/${momentId}/${currentUserId.value}`)
    
    if (response.data.code === 200) {
      const data = response.data.data
      if (!data) {
        error.value = '朋友圈不存在或已被删除'
        return
      }
      userName.value = data.currentUsername
      avatar.value = data.currentAvatar
      moment.value = {
        id: data.id,
        user: {
          id: data.userId,
          name: data.username,
          avatar: data.avatar
        },
        text: data.title,
        images: data.type === 1 && data.fileUrl ? data.fileUrl.split(',').filter((url: string) => url.trim()) : [],
        video: data.type === 2 ? data.fileUrl : '',
        videoPoster: '',
        location: data.isLocation === 1 ? data.address : '',
        time: formatTime(data.createTime),
        likes: (data.likeUserList || []).map((like: any) => ({
          id: like.userId,
          name: like.username,
          avatar: like.avatar 
        })),
        comments: (data.commentList || []).map((comment: any) => ({
          id: comment.id,
          user: {
            id: comment.userId,
            name: comment.username,
            avatar: comment.avatar
          },
          text: comment.content,
          time: formatTime(comment.createTime),
          replyTo: comment.pusername,
          pid: comment.pid
        }))
      }
      
      // 检查当前用户是否已点赞
      isLiked.value = data.isLike === 1
    } else {
      error.value = response.data.message || '加载失败'
    }
  } catch (err: any) {
    console.error('加载朋友圈详情失败:', err)
    error.value = err.response?.data?.message || '网络连接失败，请检查网络后重试'
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; 
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 组件挂载时加载数据
onMounted(() => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未检测到登录态，请先登录');
    return;
  }
  currentUserId.value = getUserIdFromToken(token);
  loadMomentDetail()
})
</script>

<style scoped>
.moment-detail-container {
  min-height: 100vh;
  background: white;
  padding-bottom: 80px; /* 为底部固定输入框留出空间 */
}

/* 头部 */
.detail-header {
  display: flex;
  align-items: center;
  padding: 8px 20px;
  border-bottom: 1px solid #eee;
  background: white;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  justify-content: center;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  color: #333;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

.back-icon {
  font-size: 24px;
  font-style: normal;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 内容 */
.detail-content {
  padding: 20px;
  margin-top: 60px; /* 为固定头部留出空间 */
}

/* 用户区域 */
.user-section {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  margin-right: 12px;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}



/* 文字内容 */
.text-content {
  font-size: 16px;
  line-height: 1.4;
  color: #333;
  white-space: pre-wrap;
  margin-top: 4px;
}

/* 媒体内容 */
.media-content {
  margin-left: 62px;
  margin-bottom: 15px;
}

/* 时间和操作按钮区域 */
.time-actions-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0 0 0;
}

.post-time {
  font-size: 13px;
  color: #999;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.2s;
}

.action-btn:hover {
  background: #f0f0f0;
}

.like-btn.liked {
  animation: heartbeat 0.6s ease-in-out;
}

@keyframes heartbeat {
  0% { transform: scale(1); }
  25% { transform: scale(1.2); }
  50% { transform: scale(1); }
  75% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.like-icon, .delete-icon {
  font-style: normal;
}

.delete-btn-small {
  color: #ff4757;
}

/* 图片 */
.images-section {
  margin-bottom: 15px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 4px;
  width: 100%;
  max-width: 400px;
}

.image-item {
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.image-item:hover {
  transform: scale(0.98);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 视频 */
.video-section {
  margin-bottom: 15px;
}

.video-section video {
  max-width: 400px;
  width: 100%;
  border-radius: 8px;
}

/* 位置 */
.location-section {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #576b95;
  margin-bottom: 15px;
}

.location-icon {
  margin-right: 4px;
  font-style: normal;
}

/* 点赞 */
.likes-section {
  padding: 15px 20px;
  background: #f8f8f8;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.heart-icon {
  font-size: 16px;
  font-style: normal;
  flex-shrink: 0;
  margin-top: 2px;
}

.likes-avatars {
  display: flex;
  gap: 8px;
  flex: 1;
  flex-wrap: wrap;
}

.like-avatar {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  cursor: pointer;
}

/* 评论 */
.comments-section {
  padding: 20px;
}

.comments-list {
  margin-bottom: 20px;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 6px;
  gap: 8px;
  border-bottom: 1px solid #eee;
}

.comment-item.first-comment {
  padding-top: 0;
}

.comment-icon {
  font-size: 16px;
  font-style: normal;
  margin-top: 2px;
  flex-shrink: 0;
  width: 16px;
}

.comment-icon-placeholder {
  width: 16px;
  margin-top: 2px;
  flex-shrink: 0;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-user {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.4;
  color: #333;
  margin-bottom: 4px;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

.reply-btn {
  background: none;
  border: none;
  color: #576b95;
  font-size: 12px;
  cursor: pointer;
  padding: 0;
}

.reply-btn:hover {
  text-decoration: underline;
}

.reply-mention {
  color: #576b95;
  font-weight: 500;
}

/* 底部固定评论输入框 */
.comment-input-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #eee;
  padding: 12px 16px;
  z-index: 1000;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.comment-input-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.reply-indicator {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #e8f4fd;
  padding: 4px 8px;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #576b95;
}

.cancel-reply-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  font-size: 16px;
  padding: 0 4px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.cancel-reply-btn:hover {
  background: rgba(0, 0, 0, 0.1);
}

.comment-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  background: #f8f8f8;
}

.comment-input:focus {
  border-color: #576b95;
  background: white;
}

.send-comment-btn {
  padding: 8px 16px;
  background: #576b95;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
  flex-shrink: 0;
}

.send-comment-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.send-comment-btn:not(:disabled):hover {
  background: #4a5a8a;
}

/* 更多选项 */
.more-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-btn {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border: none;
  background: #f5f5f5;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.option-btn:hover {
  background: #eee;
}

.option-btn i {
  font-size: 16px;
  font-style: normal;
}

/* 加载和错误状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  margin-top: 60px; /* 为固定头部留出空间 */
}

.loading-spinner {
  font-size: 16px;
  color: #999;
}

.error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  gap: 16px;
  margin-top: 60px; /* 为固定头部留出空间 */
}

.error-message {
  font-size: 16px;
  color: #ff4757;
  text-align: center;
}

.retry-btn {
  padding: 8px 16px;
  background: #576b95;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background: #4a5a8a;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .detail-header {
    padding: 8px 15px;
  }
  

  
  .detail-content {
    padding: 15px;
    margin-top: 55px; /* 为移动端固定头部留出空间 */
  }
  
  .comments-section {
    padding: 15px;
    background: #f8f8f8;
    border-top: 1px solid #eee;
  }
  
  .likes-section {
    padding: 12px 15px;
  }
  

  
  .like-avatar {
    width: 36px;
    height: 36px;
  }
  
  .images-grid {
    max-width: 300px;
  }
  
  .media-content {
    margin-left: 52px;
  }
  
  .user-avatar {
    width: 40px;
    height: 40px;
  }
}
</style>
